package com.shenmazong.demoes00.task;

import com.shenmazong.demoes00.mapper.TbProductMapper;
import com.shenmazong.demoes00.pojo.TbProduct;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

@Slf4j
public class SnapJdThread extends Thread {

    private TbProductMapper _mapper;

    public void setMapper(TbProductMapper mapper) {
        _mapper = mapper;
    }

    @Override
    public void run() {
        // https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&page=5
        String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&page=5";

        try {
            Document document = Jsoup.connect(url).get();
            Element j_goodsList = document.getElementById("J_goodsList");
            Elements li = j_goodsList.getElementsByTag("li");
            for (Element e : li) {
//                String sku = e.attr("data-sku");
//                System.out.println(sku);
//                System.out.println(e);

                try{
                    //-- 价格
                    Element pprice = e.getElementsByClass("p-price").get(0);
                    Element eprice = pprice.getElementsByTag("i").get(0);
                    String price = eprice.text();
                    System.out.println("price:"+price);

                    //-- 产品信息
                    Element pname = e.getElementsByClass("p-name").get(0);
                    Element em = pname.getElementsByTag("em").get(0);
                    String info = em.text();
                    System.out.println("info:"+info);

                    //-- 产品名字
                    Element pshop = e.getElementsByClass("p-shop").get(0);
                    String name = pshop.text();
                    System.out.println("name:"+name);

                    //-- 检查数据是否存在
                    //.....

                    //-- 写入数据库
                    TbProduct product = new TbProduct();
                    product.setName(name);

                    int dot = price.lastIndexOf('.');
                    String price1 = price.substring(0, dot);

                    product.setPrice(Integer.parseInt(price1));
                    product.setInfo(info);

                    _mapper.insert(product);
                }
                catch (Exception e1) {
                    continue;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        log.info("jd 抓取完成了！！！");
    }
}
